package com.swing.desktopapp;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Scanner;

public class UserServiceImpl implements UserService {

	private Formatter formatter = null;
	private OutputStream outputStream = null;
	private static UserService userServiceImpl = new UserServiceImpl();

	private UserServiceImpl() {

		try {
			outputStream = new FileOutputStream(new File("UserRecords.txt"),
					true);
			formatter = new Formatter(outputStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static UserService getInstance() {
		return userServiceImpl;
	}

	@Override
	public void create(User user) throws IOException {
		formatter.format("%s\t%s\t%s\t%s\n", user.getUserName(),
				user.getPassword(), user.getQuestion(), user.getAnswer());
		formatter.flush();

	}

	@Override
	public List<User> getAll() {

		List<User> list = new ArrayList<User>();
		Scanner scanner = null;

		try {
			scanner = new Scanner(new File("UserRecords.txt"));

			while (scanner.hasNext()) {

				User user = new UserImpl();
				user.setUserName(scanner.next());
				user.setPassword(scanner.next());
				user.setQuestion(scanner.next());
				user.setAnswer(scanner.next());

				list.add(user);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {

			if (scanner != null) {
				scanner.close();
			}
		}

		return list;
	}
}
